<?php

if(!defined('IN_DISCUZ')) exit('Access Denied');

global $_G;
$uid = $_G['uid'];
if(!$uid) {
    $template_name = defined('IN_MOBILE') && IN_MOBILE ? 'erling_qd:touch/login_prompt' : 'erling_qd:login_prompt';
    include template($template_name);
    return;
}
$plugin_xml = file_get_contents(DISCUZ_ROOT.'./source/plugin/erling_qd/discuz_plugin_erling_qd.xml');
preg_match('/<item id="version"><!\[CDATA\[(.*?)\]\]><\/item>/', $plugin_xml, $matches);
$plugin['version'] = $matches[1] ?? '';

// 获取表模型
$sign_table = C::t('#erling_qd#sings');
$sign_data = $sign_table->fetch_by_uid($uid);
// 检查是否已经签到
$is_signed = false;
$latest_sign = $sign_table->fetch_by_uid($uid);
$continuous_days = 0;
if($latest_sign && date('Y-m-d', $latest_sign['dateline']) == date('Y-m-d')) {
    $is_signed = true;
    $continuous_days = $latest_sign['continuous']; 
    $credit = $latest_sign['credit'];
}

// 获取用户签到统计数据
$total_days = $sign_table->get_total_days($uid);
// $month_days = $sign_table->get_month_days($uid);
$month_user_info = $sign_table->get_month_user_info($uid);

// 处理签到数据，添加checked状态
$processed_month_data = array();
$current_month = date('Y-m');
$days_in_month = date('t', strtotime($current_month));

// 将原始数据转换为以日期为键的数组
$sign_data_map = array();
foreach($month_user_info as $item) {
    $day = date('j', $item['dateline']);
    $sign_data_map[$day] = $item;
}

// 生成完整月份数据
for($i = 1; $i <= $days_in_month; $i++) {
    if(isset($sign_data_map[$i])) {
        $processed_month_data[] = array(
            'dateline' => $sign_data_map[$i]['dateline'],
            'credit' => $sign_data_map[$i]['credit'],
            'checked' => 1
        );
    } else {
        $processed_month_data[] = array(
            'dateline' => strtotime($current_month . '-' . $i),
            'credit' => 0,
            'checked' => 0
        );
    }
}




// 全局用户统计查询
$today_count = $sign_table->get_today_count();
$month_count = $sign_table->get_month_count();


// 模板数据
// $template_data = array(
//     'is_signed' => $is_signed,
//     'credit' => $credit??0,
//     'continuous_days' => $continuous_days,
//     'total_days' => $total_days,
//     'month_days' => $month_days,
//     'today_count' => $today_count,
//     'month_count' => $month_count
// );
$template_name = defined('IN_MOBILE') && IN_MOBILE ? 'erling_qd:touch/sign_in' : 'erling_qd:sign_in';
include template($template_name, $template_data);